package com.wsx.ones.zone.category.dao.impl;

import com.google.common.base.Strings;
import com.wsx.ones.common.util.DateUtil;
import com.wsx.ones.zone.category.dao.CategoryDao;
import com.wsx.ones.zone.category.model.CateSearch;
import com.wsx.ones.zone.category.model.mongo.ZoneCate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Created by wangshuaixin on 16/12/29.
 */
@Repository
public class CategoryDaoImpl implements CategoryDao {

    @Autowired
    private MongoTemplate mongoTemplate;


    public void saveCate(ZoneCate zoneCate) {
        mongoTemplate.save(zoneCate);
    }

    public List<Map> getAllCates(Integer pageNo, Integer pageSize) {

        Query query = new Query();
        query.skip((pageNo - 1) * pageSize);
        query.limit(pageSize);

        query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "_id")));

        return mongoTemplate.find(query, Map.class, "zone_cate");
    }

    public List<Map> getSearchCates(CateSearch search) {
        Query query = new Query();
        if (!Strings.isNullOrEmpty(search.getName())) {
            query.addCriteria(Criteria.where("name").regex(search.getName()));
        }
        if (!Strings.isNullOrEmpty(search.getAtime())) {
            query.addCriteria(Criteria.where("atime").lte(DateUtil.getDateFromStr(search.getAtime())));
        }

        query.skip((search.getPageNo() - 1) * search.getPageSize());
        query.limit(search.getPageSize());

        query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "_id")));

        return mongoTemplate.find(query, Map.class, "zone_cate");
    }
}
